package com.ruoyi.mail.service.impl;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.mail.service.IMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Date;

@Service
public class MailServiceImpl implements IMailService {

    @Autowired
    JavaMailSender mailSender;

    @Autowired
    private RuoYiConfig ruoyiConfig;

    @Autowired
    private MailProperties mailProperties;

    @Override
    public boolean sendMail(String sendTo,String title,String content,String filePath) {

        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(mailProperties.getUsername(), ruoyiConfig.getName());
            mimeMessageHelper.setTo(sendTo);
            mimeMessageHelper.setSubject(title);
            mimeMessageHelper.setSentDate(new Date());
            mimeMessageHelper.setText(content, true);
            if (filePath != null) {
                File file = new File(filePath);
                mimeMessageHelper.addAttachment(file.getName(), file);
            }
            mailSender.send(mimeMessage);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
